<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>User 2 Chat</title>
    <style>
        /* 样式与User1一致，直接复用 */
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; }
        #messages { list-style: none; padding: 0; }
        #messages li { margin: 10px 0; padding: 10px; border-radius: 5px; max-width: 80%; }
        .user1-msg { background-color: #e3f2fd; margin-left: auto; }
        .user2-msg { background-color: #f5f5f5; }
        .input-container { margin-top: 20px; display: flex; gap: 10px; }
        input[type="text"] { flex-grow: 1; padding: 8px; }
        button { padding: 8px 20px; cursor: pointer; }
        .system-msg { color: #666; font-size: 0.9em; }
        #user-status { margin-top: 10px; }
        .online { color: green; }
        .offline { color: red; }
    </style>
</head>

<body>
<h1>User 2 (ID: 2)</h1>
<ul id="messages"></ul>
<div class="input-container">
    <input type="text" id="messageInput" placeholder="输入消息...">
    <button onclick="sendMessage()">发送</button>
</div>
<div id="user-status">对方状态: <span id="status-text">未知</span></div>

<script>
    // --------------------- 用户配置 ---------------------
    const userId = 2;          // 当前用户ID（User2）
    const receiverId = 1;      // 接收者ID（User1）
    let socket;
    let reconnectAttempts = 0;
    let reconnectInterval;

    // --------------------- WebSocket连接 ---------------------
    function connect() {
        // 注意：若服务端IP不同需调整（此处沿用User1的IP，实际需与服务端一致）
        socket = new WebSocket(`ws://118.178.134.24:8060/ws?userId=${userId}`);

        socket.onopen = function () {
            appendMessage("连接已建立（用户2）", "system");
            alert("连接成功！");
            reconnectAttempts = 0;
            clearInterval(reconnectInterval);
            reconnectInterval = null;
            getRecentMessages(); // 初始化获取历史消息
        };

        socket.onmessage = function (event) {
            try {
                const msg = JSON.parse(event.data);
                // 判断消息来源：User1的消息显示为右侧样式
                const isUser1 = msg.senderId === 1;
                appendMessage(msg.content, isUser1 ? "user1-msg" : "user2-msg");
            } catch (error) {
                console.error("消息解析失败:", error);
            }
        };

        socket.onclose = function () {
            appendMessage("连接已关闭（用户2）", "system");
            alert("连接已关闭！");
            if (!reconnectInterval) {
                reconnectInterval = setInterval(attemptReconnect, 60000); // 每分钟尝试重连
            }
        };

        socket.onerror = function (error) {
            console.error("WebSocket错误:", error);
        };
    }

    // --------------------- 发送消息 ---------------------
    function sendMessage() {
        const input = document.getElementById("messageInput");
        const content = input.value.trim();
        if (!content) return;

        const message = {
            senderId: userId,         // User2作为发送者
            receiverId: receiverId,   // 接收者为User1
            content: content,
            type: 1,
            status: 1,
            isCompressed: false,
            sequenceNumber: Date.now(),
            sendTime: Date.now()      // 使用时间戳
        };

        if (socket && socket.readyState === WebSocket.OPEN) {
            socket.send(JSON.stringify(message));
            appendMessage(content, "user2-msg"); // User2消息左对齐
            input.value = "";
        } else {
            alert("连接已断开，无法发送消息");
        }
    }

    // --------------------- 辅助函数 ---------------------
    function appendMessage(content, className) {
        const messages = document.getElementById("messages");
        const li = document.createElement("li");
        li.className = className;
        li.innerHTML = content;
        messages.appendChild(li);
        messages.scrollTop = messages.scrollHeight; // 自动滚动到底部
    }

    function attemptReconnect() {
        if (reconnectAttempts >= 5) {
            clearInterval(reconnectInterval);
            reconnectInterval = null;
            appendMessage("连续五分钟重连失败，停止尝试", "system");
            return;
        }
        reconnectAttempts++;
        appendMessage(`重连尝试（第${reconnectAttempts}次）`, "system");
        connect();
    }

    // --------------------- 用户状态检查 ---------------------
    function checkUserStatus() {
        // 检查User1（receiverId=1）的在线状态
        fetch(`http://127.0.0.1:8060/user-status/${receiverId}/isOnline`)
            .then(response => response.json())
            .then(data => {
                const statusText = document.getElementById("status-text");
                statusText.textContent = data ? "在线" : "离线";
                statusText.className = data ? "online" : "offline";
            })
            .catch(error => {
                console.error("状态检查失败:", error);
                statusText.textContent = "未知";
                statusText.className = "";
            });
    }

    // --------------------- 历史消息获取 ---------------------
    function getRecentMessages() {
        const endTime = new Date();
        const startTime = new Date(endTime.getTime() - 2 * 24 * 60 * 60 * 1000); // 最近两天

        fetch(`http://127.0.0.1:8060/messages/history?senderId=${userId}&receiverId=${receiverId}&startTime=${startTime}&endTime=${endTime}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    data.data.forEach(message => {
                        const isUser1 = message.senderId === 1;
                        appendMessage(message.content, isUser1 ? "user1-msg" : "user2-msg");
                    });
                } else {
                    console.error("获取历史消息失败:", data.message);
                }
            })
            .catch(error => {
                console.error("历史消息获取失败:", error);
            });
    }

    // --------------------- 初始化 ---------------------
    checkUserStatus(); // 初始状态检查
    setInterval(checkUserStatus, 10000); // 每10秒轮询状态
    connect(); // 启动WebSocket连接
</script>
</body>

</html>